<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!doctype html>
<html>
	<head>
		<title>角色授权</title>
		<link href="${ctx}/assets/css/zTreeStyle/zTreeStyle.css" type="text/css" rel="stylesheet" />
		<script src="${ctx}/assets/js/jquery.ztree.all.js" type="text/javascript"></script>
		<script src="${ctx}/assets/js/dataTables.custom.js"></script>
		<script type="text/javascript">
			var $roleID_tmp='<%=request.getParameter("ROLE_ID") %>';
			var notGrantUserTree;
			//部门树设置
		    var notGrantUserTreeSet = {
	    		view: {
		     		dblClickExpand: false,
					selectedMulti: false  // 是否允许同时选中多个节点（默认true）
				},
				check: {
					enable: true    // 节点上是否显示checkbox/radio
				},
				data: {
					key:{
					  name:"NODE_NAME"  // 节点名称的属性
					},
					simpleData: {
						enable: true, // 使用简单数据模型（array），但请注意simpleData内的参数（idKey，pIdKey，rootPId）满足父子关系
						idKey: "NODE_ID",
						pIdKey: "P_ID",
						rootPId: "-1"
					}
				},
				callback: {
					
				}
		    };
			// 添加未授权用户到角色
			function grantUserToRole(){
				// 检查授权用户项（至少一项）
				var checkNodesTmp = notGrantUserTree.getCheckedNodes();
				if(checkNodesTmp.length==0){
					notyInfo( '请先选择授权的用户(至少一项)...');
					return;
				}
				// 授权用户，存放入数组中
		        var selGrantNodes= [];
		        $.each(checkNodesTmp,function(index,node){
		        	if(!node.isParent){
		        		var nodeTmp = {'USER_ID':node.NODE_ID};
			        	// node['XXX'] = value.XXX; // josn中存入其他对象
			        	selGrantNodes.push(nodeTmp); // 插入数组
		        	}
		        });
		        // 开始授权...
		        if(selGrantNodes.length>0){
		        	 // ajax用户授权
			        var jsonObj = jQuery.parseJSON('{"ROLE_ID":"'+$roleID_tmp+'"}');
			        jsonObj['userIds'] = JSON.stringify(selGrantNodes);
				    $.ajax({
				        async : false,  
				        cache:false,  
				        type: 'POST',
				        data: $.param(jsonObj),
				        dataType : "json",  
				        url: path+"/sys/user!batchGrantUserToRole.ec",
				        error: function () {
				        	notyError('系统用户授权为角色失败!');  
				        },  
				        success:function(data){
				        	initNotGrantUserTree();
				        	$('#roleGrantUserList').dataTable().fnDraw();
				        	notySuccess(data.message);
				        }  
				    });
		        }else{
		        	notyInfo( '请先选择授权的用户(至少一项)...');
					return;
		        }
			}
			// 删除角色组的用户
			function delUserAndRoleRelated(userID){
				if(!confirm("您是否要移除该记录？")){
					return;
				}
				$.ajax({
			        async : false,  
			        cache:false,  
			        type: 'POST',
			        data	:	{'USER_ID':userID,'ROLE_ID':$roleID_tmp},
			        dataType : "json",  
			        url: path+"/sys/user!delUserAndRoleRelated.ec",
			        error: function () {
			        	notyError('系统用户授权为角色失败!');  
			        },  
			        success:function(data){
			        	initNotGrantUserTree();
			        	$('#roleGrantUserList').dataTable().fnDraw();
			        	notySuccess(data.message);
			        }  
			    });
			}
			// 初始化树...
			function initNotGrantUserTree(){
				try{
				   //加载未授权人员树
				   $.ajax({  
				        async : false,  
				        cache:false,  
				        type: 'POST',  
				        dataType : "json",  
				        url: path+"/sys/dept!getNoGrantUsers.ec",
				        data:{'ROLE_ID':$roleID_tmp},
				        error: function (xhr,textStatus,exception) {
				            alert('未授权用户数据加载失败!'+xhr.responseText);  
				        },  
				        success:function(data){
				        	if(notGrantUserTree!=null)
				        		notGrantUserTree.destroy();
				        	notGrantUserTree = $.fn.zTree.init($("#notGrantUserTree"), notGrantUserTreeSet, data);
				        	// 展开根节点
				        	notGrantUserTree.expandAll(true);
				        	//notGrantUserTree.expandNode(notGrantUserTree.getNodeByParam("P_ID",'-1',null), true, true, true);
				        }  
				    }); 
			    }catch(e){
			   		alert(e);
			    }
			}
			
			// 页面加载完成后，完成初始化界面数据操作...
			$(function(){
				// -- 用户查询  --
			    var tableConf = {
			    		sDom: "<'row-fluid'rt<'row-fluid'<'span12'<'pull-right'p>>>",
			        	mTableDivID:"#roleGrantUserList",//页面table的dom ID
			        	mDtTableName:"GRANT_USER",//数据表名
			            sAjaxSource: path+"/sys/user!getRoleGrantUsers.ec",//获取列表数据url
			            fnServerParams: function ( aoData ) {
					        aoData.push(
							        {"name": "ROLE_ID","value":$roleID_tmp}
							);
					    },
			            aoColumnDefs: [
		                   {aTargets: [5],
	                        mRender: function (data, type, row) {
	                        	var htmlCode = '';
	                        	//var hrefUrl1 = path+'/sys/user!delUserAndRoleRelated.ec?ROLE_ID='+$roleID_tmp+'&USER_ID='+row.USER_ID;
	                        	htmlCode += '<button class="btn btn-small btn-danger" onclick="delUserAndRoleRelated('+row.USER_ID+')"><i class="halflings-icon white trash"></i> 移除</a>';  
	                    	    return htmlCode;
	                       }
		                  }]
			        };
			    buildTable(tableConf);
				// -- 初始化树  --
			    initNotGrantUserTree();

			});
		</script>
	</head>
	<body>
		<div class="container-fluid">
			<div class="row-fluid">
				<div class="span12"> 	
					 <div class="row-fluid">
					 	 <!-- 组织架构 and用户-->
					 	 <div  class="span4 box" style="height:600px;overflow-y: auto;">
					 	 	<div class="box-header">
								<i class="icon-group"></i><span class="break"></span> 未授权用户
								<div class="box-icon">
									<button class="btn btn-mini btn-primary" id="btn_addSysRole" onclick="grantUserToRole()">添加到角色  <i class="icon-chevron-right"></i></button>
								</div>
							</div>
							<div class="box-content">
						 	 	<ul id="notGrantUserTree" class="ztree"></ul>
						     </div>
					 	 </div>
					 	 <!-- Role授权用户 -->
					     <div class="span8 box" style="min-height:600px;">
					 	 	<div class="box-header">
								<i class="icon-list"></i><span class="break"></span> 已授权用户
								<div class="box-icon">
									<button class="btn btn-mini grey-mint" onclick="history.go(-1)"><i class="icon-share-alt"></i> 返回</button>
								</div>
							</div>
							<div class="box-content">
						    	<table id="roleGrantUserList" class="table table-striped bootstrap-datatable datatable">
						     </table>
						    </div>
					     </div>
					 </div>
		             
				</div>
			</div>
		</div>
	</body>
</html>
